package com.jky.stmall.manger.controller.api;

import com.github.pagehelper.PageInfo;
import com.jky.stmall.manger.entity.Goods;
import com.jky.stmall.manger.entity.Result;
import com.jky.stmall.manger.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
//相当于 controller和responsebody的注解 将类作为bean放入 容器中。该类所有处理器方法 返回json数据格式
@RequestMapping("/api/goods")
public class APIGoodsController {
    @Autowired
    private GoodsService goodsService;
    @PostMapping
    public Result add(@RequestBody Goods goods){
        try{
            int code = goodsService.add(goods);
            return  Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    /**
     * 删除
     */
    @DeleteMapping
    public Result remove(Integer id){
        try {
            int code = goodsService.remove(id);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /*更新
     */
    @PutMapping
    public Result edit(@RequestBody Goods goods){
        try {
            int code = goodsService.edit(goods);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }

    }
    /**
     * 根据条件查询
     */
    @GetMapping
    public  Result get(Integer page,Integer limit ,Goods goods){
        if (page==null){
            List<Goods> list=goodsService.search(goods);
            return  Result.success(list);
        }else {
            PageInfo pageInfo=goodsService.searchByPage(page, limit, goods);
            return Result.success(pageInfo);
        }
    }
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") Integer id)  {
        Goods goods= null;
        try {
            goods = goodsService.getById(id);
            return  Result.success(goods);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }

    }



}
